﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.IO;
using ScFramework.Core;
using UnityEditor.SceneManagement;
using System;
using System.Linq;

public class Tools : Editor
{
#if UNITY_EDITOR
    [UnityEditor.Callbacks.DidReloadScripts(0)]
    static void LoadTable()
    {
        CSVMake.BuildCSVFile();
    }
#endif
    [MenuItem("Tools/Save")]
     static void SaveToLocal()
    {
        var objs = GameObject.FindObjectsOfType<MeshComp>();
        var data = new LocalData { SpecialPoints = new List<SpecialPointData>(), Tris = new List<TriData>(), Player = new PlayerData() };
      //  bool isfree = true;
        foreach (var x in objs)
        {
                data.Tris.Add(x.Tri.ToWorld(x.transform));
            data.Tris.Last().Normalize();
        /*    if (x.GetComponentInChildren<SpecialPoint>() is SpecialPoint p)
            {
                if (p.sp == Specials.Start)
                {
                    data.Player.PlayerTri = x.Tri.ToWorld(x.transform);
                    p.Type = x.Tri.Type;
                    isfree = false;
                }
            }*/
        }
        int startcnt = 0;

        var sps = GameObject.FindObjectsOfType<SpecialPoint>();
        foreach (var x in sps)
        {
            if (x.sp == Specials.Start)
            {
                startcnt++;
                if (data.Tris.Find(s => s.ContainPoint(x.transform.position)) != null)
                {
                    data.Player.PlayerTri = data.Tris.Find(s => s.ContainPoint(x.transform.position));
                    data.Player.IsFree = false;
                }
                else
                {
                    data.Player.IsFree = true;
                    data.Player.PlayerTri.Type = x.Type;
                    data.Player.PlayerTri.Points = new List<Vector2> { x.transform.position, x.transform.position, x.transform.position };
                }

                data.Player.Down = x.Down;
                data.Player.Scale = x.Scale;

            }
            else
            {
                Debug.Assert(data.Tris.FindAll(s => s.ContainPoint(x.transform.position)).Count == 1);
                data.SpecialPoints.Add(new SpecialPointData { Pos = x.transform.position, Sp = x.sp });

            }
        }
        Debug.Assert(startcnt == 1);
        data.LevelID = int.Parse(EditorSceneManager.GetActiveScene().name.Split('_')[1]);
        File.WriteAllText(Main.mapSave + EditorSceneManager.GetActiveScene().name + ".json", JsonUtility.ToJson(data));
        Debug.Log($"Save to {Main.mapSave + EditorSceneManager.GetActiveScene().name}");
    }
}
